package com.lge.clock.alarmclock; 

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.util.Log;

import com.lge.clock.R;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.OPERATOR;

/**
 *
 * Settings for the Alarm Clock.
 * @author LGE Cappuccino
 */
public class SettingsActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener, VibrateType {

	//20100824_mhkwon_TD6879_Play_Sound_in_silent_mode [[
// 20100824_mhkwon_Change_private_to_public_for_access_ALARM_STREAM_TYPE_BIT_in_AlarmAlert.java 
    public static final int ALARM_STREAM_TYPE_BIT = 1 << AudioManager.STREAM_ALARM;
//20100824_mhkwon_TD6879_Play_Sound_in_silent_mode ]]

    private static final String KEY_ALARM_IN_SILENT_MODE = "alarm_in_silent_mode";
    private static final String KEY_VOLUME_BEHAVIOR = "volume_button_setting";
    private static final String KEY_ALARM_VOLUME = "alarm_volume_setting";
//    static final String KEY_DEFAULT_RINGTONE = "default_ringtone";
    private static final String KEY_PUZZLE_MODE = "puzzle_setting";
    private Preference mweatherPref;
    
    private boolean mUseVolumeDisableMode = false;
    private String TAG = "SettingsActivity";
    
    public static final String KEY_VIBRATION_TYPE = "vibrate_type_setting"; //[6380]  
    private String mAlarmDistinctiveVibration = "0";//[6380]  

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUseVolumeDisableMode = isUseVolDisableMode();
        addPreferencesFromResource(R.xml.settings);
    }

    @Override
    protected void onResume() {
        super.onResume();
		
        if(mUseVolumeDisableMode) {
	        IntentFilter filter = new IntentFilter(
					AudioManager.RINGER_MODE_CHANGED_ACTION);
			registerReceiver(mReceiver, filter);
        }
		
        refresh();
    }

    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(mUseVolumeDisableMode)
			unregisterReceiver(mReceiver);
	}
    
    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        if (KEY_ALARM_IN_SILENT_MODE.equals(preference.getKey())) {
            CheckBoxPreference pref = (CheckBoxPreference) preference;
            int ringerModeStreamTypes = Settings.System.getInt(
            		getContentResolver(),
                    Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

           	if (pref.isChecked()) {
           		ringerModeStreamTypes &= ~ALARM_STREAM_TYPE_BIT;
            } else {
                ringerModeStreamTypes |= ALARM_STREAM_TYPE_BIT;
            }

            Settings.System.putInt(getContentResolver(),
                    Settings.System.MODE_RINGER_STREAMS_AFFECTED,
                    ringerModeStreamTypes);
            
            if(mUseVolumeDisableMode)
            	checkVolumePref();
            return true;
        }
           
        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

    public boolean onPreferenceChange(Preference pref, Object newValue) {
    	
		// suguen.hwang 2012.04.13 start [6380]
		final String key = pref.getKey();

		if (KEY_VIBRATION_TYPE.equals(key)) {
			int value = Integer.parseInt((String) newValue);
			Log.d(TAG, "vibrate value : " + value);
			try {
				Settings.System.putInt(getContentResolver(),
						DISTINCTIVE_VIBRATION_ALARM, value);

			} catch (NumberFormatException e) {
				Log.e(TAG,"could not persist incoming_distinctive_vibration setting");
			}

		}
		// suguen.hwang 2012.04.13 end [6380]
    	
        final ListPreference listPref = (ListPreference) pref;
        final int idx = listPref.findIndexOfValue((String) newValue);
        listPref.setSummary(listPref.getEntries()[idx]);
        
        return true;
    }

    private void refresh() {
        final CheckBoxPreference alarmInSilentModePref = (CheckBoxPreference) findPreference(KEY_ALARM_IN_SILENT_MODE);
        final int silentModeStreams =
        				Settings.System.getInt(getContentResolver(),
                        Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
        alarmInSilentModePref.setChecked((silentModeStreams & ALARM_STREAM_TYPE_BIT) == 0);

		//suguen.hwang 2012.04.13 start [6380]
        if(CommonUtil.isSprintOperator()){
        	mAlarmDistinctiveVibration = String.valueOf(Settings.System.getInt(getContentResolver(),
                    DISTINCTIVE_VIBRATION_ALARM, DEFAULT_VALUE));
            Log.d(TAG, "mAlarmDistinctiveVibration : "+mAlarmDistinctiveVibration);
            
            final VibrateTypeListPreference vibrate =
                (VibrateTypeListPreference) findPreference(KEY_VIBRATION_TYPE);
            vibrate.setValue(mAlarmDistinctiveVibration);
            vibrate.setSummary(vibrate.getEntry());
            vibrate.setOnPreferenceChangeListener(this);
        }
		//suguen.hwang 2012.04.13 end [6380]
        
        if(mUseVolumeDisableMode)
        	checkVolumePref();
       
//        final ListPreference puzzle_setting = (ListPreference) findPreference(KEY_PUZZLE_MODE);
//        puzzle_setting.setSummary(R.string.sp_puzzle_set_summary_NORMAL);
//        puzzle_setting.setOnPreferenceChangeListener(this);
//        final ListPreference snooze = (ListPreference) findPreference(KEY_ALARM_SNOOZE);
//        snooze.setSummary(snooze.getEntry());
//        snooze.setOnPreferenceChangeListener(this);
    }
    
	void checkVolumePref() {
		if (CommonUtil.getBuildOperator() != OPERATOR.DCM)
			return;

		final CheckBoxPreference alarmInSilentModePref = (CheckBoxPreference) findPreference(KEY_ALARM_IN_SILENT_MODE);

		boolean volumeEnable = true;

		if (alarmInSilentModePref != null && !alarmInSilentModePref.isChecked()) {
			int ringerMode = ((AudioManager) getSystemService(Context.AUDIO_SERVICE))
					.getRingerMode();
			if (ringerMode != AudioManager.RINGER_MODE_NORMAL)
				volumeEnable = false;
		}

		final Preference volumePref = findPreference(KEY_ALARM_VOLUME);
		if (volumePref != null)
			volumePref.setEnabled(volumeEnable);
	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(
					AudioManager.RINGER_MODE_CHANGED_ACTION)) {
				checkVolumePref();
			}
		}
	};

	/**
	 * I-DCM Limitation : Preference Menu for Alarm Volume is Disabled when Alarm should not alert.
	 * 
	 * @return
	 */
	private boolean isUseVolDisableMode() {
		if (CommonUtil.getBuildOperator() == OPERATOR.DCM)
			return true;

		return false;
	}
}